int count;
char buffer[255];

void setup(){
  Serial.begin(9600);
  count = 0;
}

void loop(){
  while(Serial.available()){
      char c = Serial.read();
      if(c != '\n' || c != '\r' || count < 255 ){
        buffer[count] = c;
        count ++;
      }else{
        //get the command
        int command = atoi(buffer[0] + "");
        int pin = atoi(buffer[1] + buffer[2] + "");
        int value = atoi(buffer[3] + buffer[4] + buffer[5] + "");
        
        //run the command
        runCommand(command, pin, value);
        //reset the buffer
        for(int x = 0; x < 255; x++){
          buffer[x] = '0';
        }
        
        count = 0;
      }
  }
}

void runCommand(int command, int pin, int value){
  switch(command){
    case 0:  //Set Pin Mode
      pinMode(pin, value == 1 ? INPUT : OUTPUT);
      break;
    case 1:  //Digital Write
      digitalWrite(pin, value == 1 ? HIGH : LOW);
      break;
    case 2:  //Digital Read
      int val = digitalRead(pin);
      Serial.write(val);
      break;
    case 3:  //Analog Read
      int val = analogRead(pin);
      Serial.write(val);
      break;
    case 4: //Analog Write
      analogWrite(pin, value);
  }
}
